package com.lancoo.edu.platform.operation.commons.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * @author: zhang.ws
 * @Description: 运行命令工具类
 */
@Slf4j
public class RunCommodeUtil {

    /**
     * 运行命令
     *
     * @param commode 命令字符串（单个命令）
     */
    public static boolean run(String commode) {
        Runtime runtime = Runtime.getRuntime();
        try {
            Process exec = runtime.exec(commode);
            BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream(), Charset.forName("GBK")));
            String line;
            StringBuilder result = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                if (StringUtil.isNotBlank(line)) {
                    result.append(line).append(" ");
                }
            }
            reader.close();
            // 当执行不成功时、获取不成功的信息
            if (StringUtil.isBlank(result)) {
                BufferedReader readerError = new BufferedReader(new InputStreamReader(exec.getErrorStream(), Charset.forName("GBK")));
                String lineError;
                StringBuilder resultError = new StringBuilder();
                while ((lineError = readerError.readLine()) != null) {
                    if (StringUtil.isNotBlank(lineError)) {
                        resultError.append(lineError).append(" ");
                    }
                }
                readerError.close();
                log.info("【运行命令失败：{}，返回：{}】", commode, resultError);
                return false;
            }
            log.info("【运行命令成功：{}，返回：{}】", commode, result);
            return true;
        } catch (IOException e) {
            log.error("【运行命令失败：命令：{}】", commode, e);
        }
        return false;
    }
}
